


using System;
using System.Threading;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Ruminate.GUI.Framework;
using SharedLib.Engine;
using SharedLib.Network.Client;
using Krypton;
using SharedLib.UI;
using SharedLib.Helpers;
using System.Runtime.InteropServices;
using SharedLib;
using Krypton.Lights;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;


namespace GameStateManagement
{
    /// <summary>
    /// This screen implements the actual game logic. It is just a
    /// placeholder to get the idea across: you'll probably want to
    /// put some more interesting gameplay in here!
    /// </summary>
    class GameplayScreen : GameScreen
    {

        public ClientAudioManager audiomanager;
        public ContentManager conmanager;
        public ClientProperties Pbag;
        public Camera2D Camera;
        SpriteFont font;
        ContentManager content;

        Texture2D playerTexture;

        Krypton.KryptonEngine Krypton;
        float ambiant = 0.1f;
        public Texture2D lightTexture;

        public RuminateGUI gui;
        public RenderTarget2D Minimap;
        public Texture2D CursorMiniMap;
        public Texture2D MiniMapContour;

        private Vector2 mouseInitClick;

        public int handle;

        public int posCenterX;
        public int posCenterY;

        public Light2D myLight;

        Random random = new Random();

        float pauseAlpha;


        public GameplayScreen(String IP,String playerName)
        {
            TransitionOnTime = TimeSpan.FromSeconds(1.5);
            TransitionOffTime = TimeSpan.FromSeconds(0.5);

            Pbag = new ClientProperties(IP, playerName);
        }

        public override void LoadContent()
        {
            if (conmanager == null)
                conmanager = new ContentManager(ScreenManager.Game.Services, "Content");

            Minimap = new RenderTarget2D(ScreenManager.GraphicsDevice, 3 * Constants.CHUNK_WIDTH * Constants.MAP_TILE_SIZE, 3 * Constants.CHUNK_HEIGHT * Constants.MAP_TILE_SIZE, true, ScreenManager.GraphicsDevice.DisplayMode.Format, DepthFormat.Depth24);

          

            font = conmanager.Load<SpriteFont>("UI/UI");

            CursorMiniMap = conmanager.Load<Texture2D>("Texture/minimap_cursor");
            MiniMapContour = conmanager.Load<Texture2D>("Texture/minimap");

            audiomanager = new ClientAudioManager();
            handle = (int)ScreenManager.Game.Window.Handle;
            Camera = new Camera2D();
            
            Krypton = new KryptonEngine(ScreenManager.Game, "Effects/KryptonEffect"); ;

            Pbag.ObjectsBox.Add("minimap", Minimap);
            Pbag.ObjectsBox.Add("krypton", Krypton);
            Pbag.ObjectsBox.Add("screenmanager", ScreenManager);

            gui = new RuminateGUI(ScreenManager.Game);
            gui.SetTheme(new NewTheme(conmanager, gui));
            Krypton.Initialize();

            SharedLib.Engine.Tile.LoadContent(conmanager);
            playerTexture = conmanager.Load<Texture2D>("Texture/player");
            posCenterX = ScreenManager.GraphicsDevice.Viewport.Width / 2 - playerTexture.Width / 2;
            posCenterY = ScreenManager.GraphicsDevice.Viewport.Height / 2 - playerTexture.Height / 2;
            lightTexture = LightTextureBuilder.CreatePointLight(ScreenManager.GraphicsDevice, 512);

            Pbag.ObjectsBox.Add("lightTexture", lightTexture);

            while (Pbag.State != ClientState.InGame)
            {
                Pbag.ClientListener.Update();
            }

            ScreenManager.Game.ResetElapsedTime();

            this.myLight = new Light2D()
            {
                Texture = lightTexture,
                Range = 200,
                Color = Color.White,
                Intensity = 1f,
                Angle = 0,

                X = Pbag.Player.Position.X,
                Y = Pbag.Player.Position.Y
            };
            Krypton.Lights.Add(myLight);
        }


        public override void UnloadContent()
        {
            conmanager.Unload();
        }

        public void kryptonConfig()
        {
            Krypton.AmbientColor = Color.Lerp(new Color(10, 10, 10), new Color(250, 250, 250), ambiant);
            Krypton.SpriteBatchCompatablityEnabled = true;
            Krypton.Matrix = Camera.get_transformation(ScreenManager.GraphicsDevice);
            Krypton.CullMode = CullMode.None;
            Krypton.Bluriness = 3;
            Krypton.LightMapPrepare();
        }

        private void UpdateKeyboard(GameTime gametime)
        {
            Vector2 nextMove = Vector2.Zero;

            if (SharedLib.Helpers.Input.isHold(Microsoft.Xna.Framework.Input.Keys.Left) || SharedLib.Helpers.Input.isHold(Microsoft.Xna.Framework.Input.Keys.Q))
                nextMove += new Vector2(-1, 0);

            if (SharedLib.Helpers.Input.isHold(Microsoft.Xna.Framework.Input.Keys.Right) || SharedLib.Helpers.Input.isHold(Microsoft.Xna.Framework.Input.Keys.D))
                nextMove += new Vector2(1, 0);

            if (SharedLib.Helpers.Input.isHold(Microsoft.Xna.Framework.Input.Keys.Up) || SharedLib.Helpers.Input.isHold(Microsoft.Xna.Framework.Input.Keys.Z))
                nextMove += new Vector2(0, -1);

            if (SharedLib.Helpers.Input.isHold(Microsoft.Xna.Framework.Input.Keys.Down) || SharedLib.Helpers.Input.isHold(Microsoft.Xna.Framework.Input.Keys.S))
                nextMove += new Vector2(0, 1);

            if (SharedLib.Helpers.Input.isHold(Microsoft.Xna.Framework.Input.Keys.LeftShift) || SharedLib.Helpers.Input.isHold(Microsoft.Xna.Framework.Input.Keys.RightShift))
                nextMove *= Constants.PLAYER_SPEED_MULTIPLIER;

            nextMove *= Constants.PLAYER_MOVE_MULTIPLIER;

            nextMove = Vector2.Transform(nextMove, Matrix.CreateRotationZ(-Pbag.Player.Rotation));
            
            

            if (nextMove != Vector2.Zero )
            {

                bool moveOK = true;

                Vector2 tmpPosition = Pbag.Player.Position + nextMove;
                Rectangle playerRectangle = new Rectangle((int)(tmpPosition.X + playerTexture.Width / 4), (int)(tmpPosition.Y + playerTexture.Height / 4), (int)(playerTexture.Width), (int)(playerTexture.Height));


                List<Tile> tuilesProches = new List<Tile>();
                foreach (var item in Pbag.WorldManager.Zone.Layers.Where(l => l.Type == LayerType.Collision).ToList())
                {
                    tuilesProches.AddRange(item.Tiles.Where(t => SharedLib.Helpers.Math.Distance2D((int)Pbag.Player.Position.X, (int)Pbag.Player.Position.Y, (int)t.Position.X, (int)t.Position.Y) < Constants.PLAYER_TEXTURE_SIZE  + Constants.TILE_SIZE).ToList());
                }

                foreach (var item in tuilesProches)
                {
                    RotatedRectangle tileRectangle = new RotatedRectangle( new Rectangle((int)item.Position.X, (int)item.Position.Y, Constants.TILE_SIZE, Constants.TILE_SIZE),-Pbag.Player.Rotation);
                    if (tileRectangle.Intersects(playerRectangle))
                    {
                        moveOK = false;
                    }
                   
                }

                if (moveOK)
                {
                    Pbag.Player.Position += nextMove;
                    Pbag.ClientSender.SendMovementUpdate();
                }
            }
        }

        private void UpdateMouse(GameTime gametime)
        {
            Rectangle rect = Krypton.Game.Window.ClientBounds;
            rect.Width += rect.X;
            rect.Height += rect.Y;

            float ScrollWheelChange = (float)((SharedLib.Helpers.Input.getLastMouseState().ScrollWheelValue -
                                  SharedLib.Helpers.Input.getMouse().ScrollWheelValue)) / 1200;

            if (ScrollWheelChange != 0)
                Camera.Zoom += ScrollWheelChange;

            if (SharedLib.Helpers.Input.getMouse().RightButton == Microsoft.Xna.Framework.Input.ButtonState.Pressed)
            {
                ClipCursor(ref rect);
                if (mouseInitClick != Vector2.Zero)
                {
                    int ecartX = SharedLib.Helpers.Input.getMouse().X - (int)mouseInitClick.X;
                    int width = ScreenManager.GraphicsDevice.Viewport.Width;

                    float ecartAbs = (float)ecartX / (float)width;

                    Pbag.Player.Rotation -= ecartAbs / Constants.PLAYER_ROTATION_FOV;

                    Pbag.ClientSender.SendRotationUpdate();
                }

                mouseInitClick = new Vector2(SharedLib.Helpers.Input.getMouse().X, SharedLib.Helpers.Input.getMouse().Y);
            }
            else
            {
                mouseInitClick = Vector2.Zero;
                Rectangle fullSize = new Rectangle(int.MinValue / 2, int.MinValue / 2, int.MaxValue, int.MaxValue);
                ClipCursor(ref fullSize);
            }

            //target
            if (SharedLib.Helpers.Input.LeftMousePressed())
            {

                Pbag.Player.Target = null;
                Vector2 mousePosition = new Vector2(SharedLib.Helpers.Input.getMouse().X, SharedLib.Helpers.Input.getMouse().Y);
                Vector2 worldPosition = Vector2.Transform(mousePosition, Matrix.Invert(Camera.get_transformation(ScreenManager.GraphicsDevice)));

                Rectangle mouseRectangle = new Rectangle((int)worldPosition.X - 1, (int)worldPosition.Y - 1, 3, 3);

                foreach (var item in Pbag.WorldManager.entitiesList.Where(p => SharedLib.Helpers.Math.Distance2D((int)p.Value.Position.X, (int)p.Value.Position.Y, (int)Pbag.Player.Position.X, (int)Pbag.Player.Position.Y) < 1000).ToList())
                {
                    RotatedRectangle targetRectangle = new RotatedRectangle(new Rectangle((int)item.Value.Position.X - playerTexture.Width / 2, (int)item.Value.Position.Y - playerTexture.Height / 2, playerTexture.Width, playerTexture.Height), item.Value.Rotation);
                    if (targetRectangle.Intersects(mouseRectangle) && item.Value.Selectable)
                    {
                        Pbag.Player.Target = (Creature)item.Value;
                    }
                    if (Pbag.Player.Target != null)
                        break;
                }

            }
            


        }


        public override void Update(GameTime gameTime, bool otherScreenHasFocus,
                                                       bool coveredByOtherScreen)
        {
            base.Update(gameTime, otherScreenHasFocus, false);
            Pbag.ClientListener.Update();
            Pbag.WorldManager.Update(gameTime);

            if (Pbag.State == ClientState.InGame)
            {
                if (WindowHasFocus())
                {
                    UpdateKeyboard(gameTime);
                    UpdateMouse(gameTime);

                    createPlayersLights();
                    createHulls();

                    gui.Update();
                }
            }
        }




        public override void Draw(GameTime gameTime)
        {
            ScreenManager.GraphicsDevice.Clear(ClearOptions.Target,
                                               Color.CornflowerBlue, 0, 0);

            if (Pbag.State == ClientState.InGame)
            {
                // draw background with grass
                


                Vector2 decalPosition = new Vector2(0, Constants.PLAYER_DRAWING_DECAL);
                decalPosition = Vector2.Transform(decalPosition, Matrix.CreateRotationZ(-Pbag.Player.Rotation));
                Camera.Pos = Pbag.Player.Position - decalPosition;
                Camera.Rotation = Pbag.Player.Rotation;

                kryptonConfig();

                ScreenManager.GraphicsDevice.Clear(Color.Black);
                ScreenManager.SpriteBatch.Begin(SpriteSortMode.Immediate,
                            BlendState.AlphaBlend,
                            null,
                            null,
                            null,
                            null,
                            Camera.get_transformation(ScreenManager.GraphicsDevice));

                drawAround();

                foreach (var item in Pbag.WorldManager.entitiesList.Where(e=>e.Value.Type == EntityType.Monster || e.Value.Type == EntityType.Player).ToList())
                {
                    ScreenManager.SpriteBatch.Draw(playerTexture, new Rectangle((int)item.Value.Position.X, (int)item.Value.Position.Y, playerTexture.Width, playerTexture.Height), new Rectangle(0, 0, playerTexture.Width, playerTexture.Height), Color.White, -item.Value.Rotation - MathHelper.PiOver2, new Vector2(playerTexture.Width / 2, playerTexture.Height / 2), SpriteEffects.None, 0f);
                }
                
                //ScreenManager.SpriteBatch.Draw(playerTexture, new Rectangle((int)(Pbag.Player.Position.X), (int)(Pbag.Player.Position.Y), playerTexture.Width, playerTexture.Height), new Rectangle(0, 0, playerTexture.Width, playerTexture.Height), Color.White, -Pbag.Player.Rotation - MathHelper.PiOver2, new Vector2(playerTexture.Width / 2, playerTexture.Height / 2), SpriteEffects.None, 0f);

                ScreenManager.SpriteBatch.End();

                Krypton.Draw(gameTime);


                ScreenManager.SpriteBatch.Begin();
                ScreenManager.SpriteBatch.Draw(playerTexture, new Rectangle((int)(posCenterX+playerTexture.Width / 2), (int)(posCenterY + Constants.PLAYER_DRAWING_DECAL+playerTexture.Height / 2), playerTexture.Width, playerTexture.Height), new Rectangle(0, 0, playerTexture.Width, playerTexture.Height), Color.White, - MathHelper.PiOver2, new Vector2(playerTexture.Width / 2, playerTexture.Height / 2), SpriteEffects.None, 0f);
                DrawGUI();
                ScreenManager.SpriteBatch.End();

                
                gui.Draw();
            }

            if (TransitionPosition > 0 || pauseAlpha > 0)
            {
                float alpha = MathHelper.Lerp(1f - TransitionAlpha, 1f, pauseAlpha / 2);

                ScreenManager.FadeBackBufferToBlack(alpha);
            }
            DebugDraw();

        }

        private void DrawGUI()
        {
            Vector2 mousePosition = new Vector2(SharedLib.Helpers.Input.getMouse().X, SharedLib.Helpers.Input.getMouse().Y);
            Vector2 worldPosition = Vector2.Transform(mousePosition, Matrix.Invert(Camera.get_transformation(ScreenManager.GraphicsDevice)));

            ScreenManager.SpriteBatch.DrawString(font, worldPosition.X.ToString() + " " + worldPosition.Y.ToString(), new Vector2(0, 200), Color.Red); 


            //Players Bars
            Texture2D WhiteTexture = TextureGenerator.getColorTexture(ScreenManager.GraphicsDevice, Color.White);

            ScreenManager.SpriteBatch.Draw(WhiteTexture, new Rectangle(0, 30, 150, 10), new Rectangle(0, 0, 1, 1), Color.Gray);
            ScreenManager.SpriteBatch.Draw(WhiteTexture, new Rectangle(0, 50, 150, 10), new Rectangle(0, 0, 1, 1), Color.Gray);

            float pourcentHP = (float)((float)Pbag.Player.HP / (float)Pbag.Player.HPMAX);
            float pourcentMana = (float)((float)Pbag.Player.Mana / (float)Pbag.Player.ManaMAX);

            ScreenManager.SpriteBatch.DrawString(font, Pbag.Player.Name, new Vector2(0, 0), Color.Green);
            ScreenManager.SpriteBatch.Draw(WhiteTexture, new Rectangle(0, 30, (int)(pourcentHP * 150), 10), new Rectangle(0, 0, 1, 1), Constants.HPColor);
            ScreenManager.SpriteBatch.Draw(WhiteTexture, new Rectangle(0, 50, (int)(pourcentMana * 150), 10), new Rectangle(0, 0, 1, 1), Constants.ManaColor);

            //Targets Bars
            if (Pbag.Player.Target != null)
            {
                ScreenManager.SpriteBatch.Draw(WhiteTexture, new Rectangle(200, 30, 150, 10), new Rectangle(0, 0, 1, 1), Color.Gray);
                ScreenManager.SpriteBatch.Draw(WhiteTexture, new Rectangle(200, 50, 150, 10), new Rectangle(0, 0, 1, 1), Color.Gray);

                float pourcentTargetHP = (float)((float)Pbag.Player.Target.HP / (float)Pbag.Player.Target.HPMAX);
                float pourcentTargetMana = (float)((float)Pbag.Player.Target.Mana / (float)Pbag.Player.Target.ManaMAX);

                ScreenManager.SpriteBatch.DrawString(font, Pbag.Player.Target.Name, new Vector2(200, 0), Color.Green);
                ScreenManager.SpriteBatch.Draw(WhiteTexture, new Rectangle(200, 30, (int)(pourcentTargetHP * 150), 10), new Rectangle(0, 0, 1, 1), Constants.HPColor);
                ScreenManager.SpriteBatch.Draw(WhiteTexture, new Rectangle(200, 50, (int)(pourcentTargetMana * 150), 10), new Rectangle(0, 0, 1, 1), Constants.ManaColor);

            }

          
            Int32 distanceX = (int)Pbag.Player.Position.X - (int)Pbag.WorldManager.Zone.Layers[0].Tiles[0].Position.X +Constants.PLAYER_TEXTURE_SIZE;
            Int32 distanceY = (int)Pbag.Player.Position.Y - (int)Pbag.WorldManager.Zone.Layers[0].Tiles[0].Position.Y +Constants.PLAYER_TEXTURE_SIZE;

            float pourcentX = (float)((float)3 * (float)Constants.CHUNK_WIDTH * (float)Constants.MAP_TILE_SIZE) / (float)((float)3 * (float)Constants.CHUNK_WIDTH * (float)Constants.TILE_SIZE);
            float pourcentY = (float)((float)3 * (float)Constants.CHUNK_WIDTH * (float)Constants.MAP_TILE_SIZE) / (float)((float)3 * (float)Constants.CHUNK_HEIGHT * (float)Constants.TILE_SIZE);

            Int32 miniDistanceX = (int)(distanceX * pourcentX);
            Int32 miniDistanceY = (int)(distanceY * pourcentY)/2;

            Vector2 ecart = new Vector2(miniDistanceX, miniDistanceY) - new Vector2(Minimap.Width / 2, Minimap.Height / 2); 

            Vector2 fullsizemap = new Vector2(3 * Constants.CHUNK_WIDTH * Constants.TILE_SIZE, 3 * Constants.CHUNK_HEIGHT * Constants.TILE_SIZE);
            Vector2 minimapesize = new Vector2(3 * Constants.CHUNK_WIDTH * Constants.MAP_TILE_SIZE, 3 * Constants.CHUNK_HEIGHT * Constants.MAP_TILE_SIZE);

            Vector2 cursorMinimapPosition = new Vector2(ScreenManager.GraphicsDevice.Viewport.Width - ((float)Minimap.Width / 2f), (float)Minimap.Height / 2f);

            Rectangle minimapZoneDraw = new Rectangle((int)cursorMinimapPosition.X - Constants.MAP_SIZE.X / 2, (int)cursorMinimapPosition.Y - Constants.MAP_SIZE.Y / 2, Constants.MAP_SIZE.X, Constants.MAP_SIZE.Y);
            Rectangle minimapDecoupZone = new Rectangle((Minimap.Width - Constants.MAP_SIZE.X) / 2 + (int)ecart.X, (Minimap.Height - Constants.MAP_SIZE.Y) / 2 + (int)ecart.Y, Constants.MAP_SIZE.X, Constants.MAP_SIZE.Y);


            ScreenManager.SpriteBatch.Draw((Texture2D)Minimap, minimapZoneDraw,minimapDecoupZone,Color.White);

            ScreenManager.SpriteBatch.Draw(CursorMiniMap, new Rectangle((int)cursorMinimapPosition.X, (int)cursorMinimapPosition.Y, CursorMiniMap.Width, CursorMiniMap.Height), new Rectangle(0, 0, CursorMiniMap.Width, CursorMiniMap.Height), Color.Red, -Pbag.Player.Rotation - MathHelper.PiOver2, new Vector2(CursorMiniMap.Width / 2, CursorMiniMap.Height / 2), SpriteEffects.None, 0f);
        }



        public static bool initHulls = false;
        //create hulls in player viewport
        private void createHulls()
        {
            if (!initHulls)
            {
                Vector2 _position = Pbag.Player.Position;

                Krypton.Hulls.Clear();
                List<Tile> tuileProches = new List<Tile>();
                foreach (var item in Pbag.WorldManager.Zone.Layers.Where(l => l.Type == LayerType.Collision).ToList())
                {
//tuileProches.AddRange(item.Tiles.Where(t => SharedLib.Helpers.Math.Distance2D((int)Pbag.Player.Position.X, (int)Pbag.Player.Position.Y, (int)t.Position.X, (int)t.Position.Y) < 1000).ToList());
                    tuileProches.AddRange(item.Tiles);
                }
                
                foreach (var item in tuileProches)
                {
                    var hull = ShadowHull.CreateRectangle(Vector2.One);
                    hull.Position.X = item.Position.X;
                    hull.Position.Y = item.Position.Y;
                    hull.Scale.X = SharedLib.Constants.TILE_SIZE;
                    hull.Scale.Y = SharedLib.Constants.TILE_SIZE;

                    Krypton.Hulls.Add(hull);
                }
                initHulls = true;
            }
        }

        //draw light for each players
        private void createPlayersLights()
        {

            Krypton.Lights.Clear();
            List<KeyValuePair<long,Entity>> lumieres = Pbag.WorldManager.entitiesList.Where(e => e.Value.Type == EntityType.Light).ToList();
            foreach (var item in lumieres)
            {
                Light2D tmp = ((Light)item.Value).KryptonLight;
                Krypton.Lights.Add(tmp);
            }
            myLight.Position = new Vector2(Pbag.Player.Position.X, Pbag.Player.Position.Y);
            Krypton.Lights.Add(myLight);
        }

        //draw only sprite in player viewport
        private void drawAround()
        {
            Vector2 _position = Pbag.Player.Position;

            List<Tile> tuileProches = new List<Tile>();
            foreach (var item in Pbag.WorldManager.Zone.Layers.Where(l=>l.Type == LayerType.Upper || l.Type == LayerType.Background).ToList())
            {
                tuileProches.AddRange(item.Tiles.Where(t => SharedLib.Helpers.Math.Distance2D((int)Pbag.Player.Position.X, (int)Pbag.Player.Position.Y, (int)t.Position.X, (int)t.Position.Y) < 1000).ToList());
            }

            foreach (var item in tuileProches)
            {
                ScreenManager.SpriteBatch.Draw(SharedLib.Engine.Tile.getTexture(), new Rectangle((int)item.Position.X, (int)item.Position.Y, SharedLib.Constants.TILE_SIZE, SharedLib.Constants.TILE_SIZE), SharedLib.Engine.Tile.getTileRectangle(item.Value), item.Couleur, 0f, new Vector2(SharedLib.Constants.TILE_SIZE / 2, SharedLib.Constants.TILE_SIZE / 2), SpriteEffects.None, 0f);

            }
        }

        public bool WindowHasFocus()
        {
            return GetForegroundWindow() == handle;
        }

        private void DebugDraw()
        {
            Krypton.RenderHelper.Effect.CurrentTechnique = this.Krypton.RenderHelper.Effect.Techniques["DebugDraw"];
            ScreenManager.GraphicsDevice.RasterizerState = new RasterizerState()
            {
                CullMode = CullMode.None,
                FillMode = FillMode.WireFrame,
            };
            if (Keyboard.GetState().IsKeyDown(Keys.H))
            {
                // Clear the helpers vertices
                this.Krypton.RenderHelper.ShadowHullVertices.Clear();
                this.Krypton.RenderHelper.ShadowHullIndicies.Clear();

                foreach (var hull in Krypton.Hulls)
                {
                    this.Krypton.RenderHelper.BufferAddShadowHull(hull);
                }


                foreach (var effectPass in Krypton.RenderHelper.Effect.CurrentTechnique.Passes)
                {
                    effectPass.Apply();
                    this.Krypton.RenderHelper.BufferDraw();
                }
            }

            if (Keyboard.GetState().IsKeyDown(Keys.L))
            {
                this.Krypton.RenderHelper.ShadowHullVertices.Clear();
                this.Krypton.RenderHelper.ShadowHullIndicies.Clear();

                foreach (Light2D light in Krypton.Lights)
                {
                    this.Krypton.RenderHelper.BufferAddBoundOutline(light.Bounds);
                }

                foreach (var effectPass in Krypton.RenderHelper.Effect.CurrentTechnique.Passes)
                {
                    effectPass.Apply();
                    this.Krypton.RenderHelper.BufferDraw();
                }
            }
        }

        [DllImport("user32.dll")]
        public static extern int GetForegroundWindow();

        [DllImport("user32.dll")]
        static extern void ClipCursor(ref Rectangle rect);

    }
}
